<template>
  <div class="forgot-password-page">
    <div class="header">
      <h1 class="title">忘记密码</h1>
      <p class="subtitle">请按照步骤重置您的密码</p>
    </div>

    <a-steps
      :current="currentStep"
      class="steps"
    >
      <a-step title="输入账号" />
      <a-step title="验证身份" />
      <a-step title="重置密码" />
      <a-step title="完成" />
    </a-steps>

    <transition
      name="fade-slide"
      mode="out-in"
    >
      <div
        class="step-content"
        :key="currentStep"
      >
        <!-- 第一步：输入账号 -->
        <div
          v-if="currentStep === 0"
          class="step-form"
        >
          <a-form
            :model="form"
            layout="vertical"
          >
            <a-form-item
              label="账号"
              name="username"
            >
              <a-input
                v-model:value="form.username"
                placeholder="请输入您的账号"
                size="large"
              >
                <template #prefix>
                  <user-outlined />
                </template>
              </a-input>
            </a-form-item>
          </a-form>
        </div>

        <!-- 第二步：验证身份 -->
        <div
          v-if="currentStep === 1"
          class="step-form"
        >
          <a-form
            :model="form"
            layout="vertical"
          >
            <div class="masked-email">
              <span class="tip">请输入邮箱并进行验证码校验：</span>
              <span class="email">{{ maskedEmail }}</span>
            </div>

            <a-form-item
              label="完整邮箱"
              name="email"
            >
              <a-input
                v-model:value="form.email"
                placeholder="请输入完整邮箱地址"
                size="large"
              >
                <template #prefix>
                  <mail-outlined />
                </template>
              </a-input>
            </a-form-item>

            <a-form-item
              label="验证码"
              name="code"
            >
              <a-input
                v-model:value="form.code"
                placeholder="请输入验证码"
                size="large"
              >
                <template #prefix>
                  <safety-certificate-outlined />
                </template>
              </a-input>
            </a-form-item>

            <a-form-item>
              <a-button
                type="primary"
                @click="handleSendCode"
                :loading="sendingCode"
                size="large"
                block
                :disabled="isCountingDown"
              >
                {{ isCountingDown ? `重新发送(${countdown}s)` : '发送验证码' }}
              </a-button>
            </a-form-item>
          </a-form>
        </div>

        <!-- 第三步：重置密码 -->
        <div
          v-if="currentStep === 2"
          class="step-form"
        >
          <a-form
            :model="form"
            layout="vertical"
          >
            <a-form-item
              label="新密码"
              name="newPassword"
            >
              <a-input-password
                v-model:value="form.newPassword"
                placeholder="8-20位字母、数字组合"
                size="large"
              >
                <template #prefix>
                  <lock-outlined />
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item
              label="确认密码"
              name="confirmPassword"
            >
              <a-input-password
                v-model:value="form.confirmPassword"
                placeholder="请再次输入新密码"
                size="large"
              >
                <template #prefix>
                  <lock-outlined />
                </template>
              </a-input-password>
            </a-form-item>
          </a-form>
        </div>

        <!-- 第四步：完成 -->
        <div
          v-if="currentStep === 3"
          class="success-message"
        >
          <a-result
            status="success"
            title="密码重置成功！"
            :sub-title="`${countdownSeconds}秒后将自动跳转到主页`"
          >
            <template #icon>
              <check-circle-filled class="success-icon" />
            </template>
          </a-result>
        </div>
      </div>
    </transition>

    <div
      class="footer-buttons"
      v-if="currentStep < 3"
    >
      <a-button
        v-if="currentStep > 0 && currentStep < 3"
        @click="prevStep"
        size="large"
      >
        上一步
      </a-button>
      <a-button
        type="primary"
        @click="nextStep"
        :loading="submitting"
        size="large"
      >
        {{ currentStep === 2 ? '提交' : '下一步' }}
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import {
  UserOutlined,
  MailOutlined,
  LockOutlined,
  SafetyCertificateOutlined,
  CheckCircleFilled
} from '@ant-design/icons-vue'
import { getUserEmail } from '@/api/auth'
import { checkEmailCaptcha, sendEmailCaptcha } from '@/api/captcha'
import { modifyPasswordByUsername } from '@/api/user'

const router = useRouter()
const currentStep = ref(0)
const isCountingDown = ref(false)
const sendingCode = ref(false)
const submitting = ref(false)
const countdown = ref(0)
const countdownSeconds = ref(5)
const maskedEmail = ref('') // 从接口获取的脱敏邮箱

const form = reactive({
  username: '',
  email: '',
  code: '',
  uuid: '',
  newPassword: '',
  confirmPassword: ''
})

/**
 * 邮箱脱敏
 */
const desensitizeEmail = (email: string) => {
  if (!email) return ''
  const [name, domain] = email.split('@')
  return `${name.slice(0, 2)}***@${domain}`
}

/**
 * 开始倒计时
 */
const startCountdown = () => {
  isCountingDown.value = true
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      isCountingDown.value = false
      clearInterval(timer)
    }
  }, 1000)
}

/**
 * 发送验证码
 */
const handleSendCode = async () => {
  if (!form.email) {
    message.error('请输入完整邮箱地址')
    return
  }

  // 验证邮箱格式
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailReg.test(form.email)) {
    message.error('请输入有效的邮箱地址')
    return
  }

  sendingCode.value = true
  const uuid = await sendEmailCaptcha(form.email)

  if (!uuid) {
    message.error('发送验证码失败，请重新发送校验')
    sendingCode.value = false
    return
  }

  form.uuid = uuid
  message.success('验证码已发送')
  startCountdown()
  sendingCode.value = false
}

// 下一步
const nextStep = async () => {
  if (currentStep.value === 0) {
    if (!form.username) {
      message.error('请输入账号')
      return
    }

    submitting.value = true
    const res = await getUserEmail(form.username)
    if (!res) {
      message.error('账号不存在')
      submitting.value = false
      currentStep.value = 0
      return
    }
    maskedEmail.value = desensitizeEmail(res)
    currentStep.value++
    submitting.value = false
  } else if (currentStep.value === 1) {
    if (!form.email || !form.code) {
      message.error('请填写完整信息')
      return
    }

    // 验证邮箱是否匹配
    if (desensitizeEmail(form.email) !== maskedEmail.value) {
      message.error('邮箱不匹配')
      return
    }

    // 校验验证码
    const res = await checkEmailCaptcha(form.email, form.code, form.uuid)
    if (!res) {
      message.error('验证码错误，请重新发送验证码进行校验')
      form.uuid = ''
      return
    }

    currentStep.value++
  } else if (currentStep.value === 2) {
    if (!form.newPassword || !form.confirmPassword) {
      message.error('请填写新密码')
      return
    }
    if (form.newPassword !== form.confirmPassword) {
      message.error('两次输入密码不一致')
      return
    }

    submitting.value = true
    try {
      await modifyPasswordByUsername({
        username: form.username,
        newPassword: form.newPassword
      })
      currentStep.value++
      handleSuccess()
    } catch {
    } finally {
      submitting.value = false
    }
  }
}

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    form.newPassword = ''
    form.confirmPassword = ''
    form.email = ''
    form.code = ''
    form.uuid = ''
    currentStep.value--
  }
}

// 成功处理
const handleSuccess = () => {
  const timer = setInterval(() => {
    countdownSeconds.value--
    if (countdownSeconds.value <= 0) {
      clearInterval(timer)
      router.push('/')
    }
  }, 1000)
}
</script>

<style scoped>
.forgot-password-page {
  max-width: 600px;
  margin: 0 auto;
  padding: 40px 24px;
  background: #fff;
}

.header {
  text-align: center;
  margin-bottom: 32px;
}

.masked-email {
  text-align: center;
  margin-bottom: 24px;
}

.masked-email .tip {
  color: #666;
}

.masked-email .email {
  font-weight: 500;
  color: #1890ff;
  margin-left: 8px;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 8px;
}

.subtitle {
  color: #6e6e73;
  font-size: 14px;
}

.steps {
  margin-bottom: 40px;
}

.step-content {
  margin-bottom: 32px;
}

.step-form {
  max-width: 400px;
  margin: 0 auto;
}

.success-message {
  text-align: center;
  padding: 40px 24px;
}

.success-icon {
  font-size: 72px;
  color: #52c41a;
  margin-bottom: 24px;
}

.footer-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 32px;
  gap: 16px;
}

.ant-radio-group {
  width: 100%;
  margin-bottom: 16px;
}

.ant-radio-wrapper {
  margin-right: 24px;
}

.ant-input-affix-wrapper {
  border-radius: 6px;
}

.ant-btn {
  border-radius: 6px;
}

.ant-steps-item-process .ant-steps-item-icon {
  background: #1890ff;
  border-color: #1890ff;
}

.ant-steps-item-finish .ant-steps-item-icon {
  border-color: #1890ff;
}

.ant-steps-item-finish .ant-steps-item-icon > .ant-steps-icon {
  color: #1890ff;
}

.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s ease;
}

.fade-slide-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}
</style>
